<?php
class Lib_XMLUtil
{
    public static function array_to_xml(array $array, $rootname='resultObject')
    {
        $r = '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'."\n".'<'.$rootname.'>'."\n";
        if(!empty($array)) foreach($array as $k=>$v) self::o2x($r,$k,$v);
        $r.='</'.$rootname.'>';
        return $r;
    }

    //貌似有bug...改使用object2array
    public static function xml_to_array($xml)
    {
    	$xml = convert_xml_encode( $xml );
        $node = simplexml_load_string($xml);
        return self::object2array($node);
    }


    //<editor-fold defaultstate="collapsed" desc="just for array_to_xml">
    private static function a2x(&$r,$k,array $v)
    {
//        if(empty($v)) return;
        $r.="<$k>"."\n";
        foreach ($v as $kk=>$vv) self::o2x($r,$kk,$vv);
        $r.="</$k>"."\n";
    }

    private static function o2x(&$r,$k,$v)
    {
    	if(is_numeric($k) && is_array($v)){
    		self::a2x($r,'row',$v);
    	}else if (is_numeric($k)) {
    		$r.="<row><![CDATA[$v]]></row>"."\n";
    	}else if(is_array($v)){
    		self::a2x($r,$k,$v);
    	}else if(is_numeric($v)){
    		$r.="<$k>$v</$k>"."\n";
    	}else if (is_bool($v)) {
    		$r.="<$k>".intval($v)."</$k>"."\n";
    	}else{
    		$r.="<$k><![CDATA[$v]]></$k>"."\n";
    	}
    }
    //</editor-fold>


	static public function object2array($object) {
		$return = null;
		if (is_array ( $object )) {
			foreach ( $object as $key => $value ) {
				$return [$key] =  self::object2array ( $value );
			}
		} else {
                        if(is_string($object)){
                                return trim(strval($object));
                        }
			$var = get_object_vars ( $object );
			if ($var) {
				foreach ( $var as $key => $value ) {
					$return [$key] =  self::object2array ( $value );
				}
			} else {
				return  trim(strval($object)); // strval and everything is fine
			}
		}

		return $return;
	}
}
?>
